package com.suncaper.shop.service;


import com.suncaper.shop.domain.*;
import com.suncaper.shop.mapper.OrderItemMapper;
import com.suncaper.shop.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DealerService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductService productService;
    private OrderExample orderExample;

    public void getOrders(HttpSession session) {
        orderExample = new OrderExample();
        List<Order> orders = orderMapper.selectByExample(orderExample);
        session.setAttribute("allOrder", orders);
    }

    public Map<String, Object> showDetail(String oid) {
        Order order = getOrderByID(oid);
        List<OrderItem> list = order.getItems();
        Map<String, Object> map = new HashMap<String, Object>();
        if (list != null && list.size() > 0) {
            map.put("itemList", list);
            return map;
        }
        return null;
    }


    public Order getOrderByID(String oid) {
        orderExample = new OrderExample();
        orderExample.createCriteria().andOidEqualTo(oid);
        List<Order> list = orderMapper.selectByExample(orderExample);
        if (list != null) {
            Order order = list.get(0);
            OrderItemExample orderItemExample = new OrderItemExample();
            orderItemExample.createCriteria().andOidEqualTo(oid);
            List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);

            for (OrderItem oi : orderItemList) {
                Product product = productService.findByPid(oi.getPid());
                oi.setProduct(product);
            }
            order.setItems(orderItemList);
            return order;
        }
        return null;
    }


    public void updateState(String oid, int state) {
        orderExample = new OrderExample();
        orderExample.createCriteria().andOidEqualTo(oid);
        List<Order> orders = orderMapper.selectByExample(orderExample);

        if (orders != null) {
            Order order = orders.get(0);
            order.setState(state);
            orderMapper.updateByPrimaryKey(order);
        }
    }
}
